package com.fh.fruit.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.GenericRequest;
import com.aliyun.oss.model.ObjectMetadata;

@Service
public class OSSUtils {
	
	
	 private static String endpoint;
	 @Value("${ENDPOINT}")
	 public void setEndpoint(String endpoint){
		OSSUtils.endpoint = endpoint;
	 }
	 private static String accessKeyId;
	 @Value("${ACCESSKEYID}")
	 public void setAccessKeyId(String accessKeyId){
		OSSUtils.accessKeyId = accessKeyId;
	 }
	 private static String accessKeySecret;
	 @Value("${ACCESSKEYSECRET}")
	 public void setAccessKeySecret(String accessKeySecret){
		OSSUtils.accessKeySecret = accessKeySecret;
	 }
	 private static String bucketName;
	 @Value("${BUCKETNAME}")
	 public void setBucketName(String bucketName){
		OSSUtils.bucketName = bucketName;
	 }
	 private static String ossUrl;
	 @Value("${oss.url}")
     public void setOssUrl(String ossUrl){
		OSSUtils.ossUrl = ossUrl;
     }
	
    
    /** 
     *  
     * @MethodName: pictureUpload 
     * @Description: 文件上传
     * @param MultipartFile  上传文件
     * @return url
     */  
    public static Map<String, Object> pictureUpload(String fileName,MultipartFile uploadFile,String type){  
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	String url=null;
		OSSClient ossClient=null;
		try {
			ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
	        CommonsMultipartFile cf= (CommonsMultipartFile)uploadFile; 
            InputStream input = cf.getInputStream();
            ObjectMetadata meta = new ObjectMetadata(); 
            meta.setContentLength(cf.getSize()); 
            meta.setContentType(type);
            meta.setCacheControl("no-cache");
            meta.setContentEncoding("utf-8"); 
            ossClient.putObject(bucketName, fileName,input,meta); 
            url = ossUrl+"/"+fileName;
            resultMap.put("error", 0);
			resultMap.put("url", url);
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("error", 1);
			resultMap.put("message", "文件上传发生异常");
		} finally {  
            ossClient.shutdown();  
        } 
        return resultMap;  
    } 
    
    
    /** 
     *  
     * @MethodName: pictureUpload 
     * @Description: 文件上传
     * @param MultipartFile  上传文件
     * @return url
     */  
    public static Map<String, Object> pictureUploadI(String fileName,InputStream in){  
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	String url=null;
		OSSClient ossClient=null;
		try {
			ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            ObjectMetadata meta = new ObjectMetadata(); 
            meta.setContentType("image/jpeg");
            meta.setCacheControl("no-cache");
            meta.setContentEncoding("utf-8"); 
            ossClient.putObject(bucketName, fileName,in,meta); 
            url = ossUrl+"/"+fileName;
            resultMap.put("error", 0);
			resultMap.put("url", url);
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("error", 1);
			resultMap.put("message", "文件上传发生异常");
		} finally {  
            ossClient.shutdown();  
        } 
        return resultMap;  
    } 
    
    /** 
     *  
     * @MethodName: deleteFile 
     * @Description: 单文件删除 
     * @param fileUrl 需要删除的文件url 
     * @return boolean 是否删除成功 
     */  
    public static boolean deleteFile(String fileUrl){  
        String bucketName = OSSUtils.getBucketName(fileUrl);       
        String fileName = OSSUtils.getFileName(fileUrl);           
        if(bucketName==null||fileName==null) return false;  
        OSSClient ossClient = null;   
        try {  
        	ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);   
            GenericRequest request = new DeleteObjectsRequest(bucketName).withKey(fileName);  
            ossClient.deleteObject(request);  
        } catch (Exception oe) {  
            oe.printStackTrace();  
            return false;  
        } finally {  
            ossClient.shutdown();  
        }  
        return true;  
    }  

    /** 
     *  
     * @MethodName: getBucketName 
     * @Description: 根据url获取bucketName 
     * @param fileUrl 文件url 
     * @return String bucketName 
     */  
    private static String getBucketName(String fileUrl){  
        String http = "http://";  
        String https = "https://";  
        int httpIndex = fileUrl.indexOf(http);  
        int httpsIndex = fileUrl.indexOf(https);  
        int startIndex  = 0;  
        if(httpIndex==-1){  
            if(httpsIndex==-1){  
                return null;  
            }else{  
                startIndex = httpsIndex+https.length();  
            }  
        }else{  
            startIndex = httpIndex+http.length();  
        }  
        int endIndex = fileUrl.indexOf(".oss-");   
        return fileUrl.substring(startIndex, endIndex);  
    }  
      
    /** 
     *  
     * @MethodName: getFileName 
     * @Description: 根据url获取fileName 
     * @param fileUrl 文件url 
     * @return String fileName 
     */  
    private static String getFileName(String fileUrl){  
        String str = "aliyuncs.com/";  
        int beginIndex = fileUrl.indexOf(str);  
        if(beginIndex==-1) return null;  
        return fileUrl.substring(beginIndex+str.length());  
    } 
    
    /** 
     *  
     * @MethodName: pictureUpload 
     * @Description: 文件上传
     * @param MultipartFile  上传文件
     * @return url
     */  
    public static Map<String, Object> pictureUpload2(String fileName,MultipartFile uploadFile,String type){  
    	Map<String, Object> resultMap = new HashMap<String, Object>();
    	String url=null;
		OSSClient ossClient=null;
		try {
			ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
	        CommonsMultipartFile cf= (CommonsMultipartFile)uploadFile; 
	        DiskFileItem fi = (DiskFileItem)cf.getFileItem(); 
	        File f = fi.getStoreLocation();
            InputStream input = new FileInputStream(f);    
            ObjectMetadata meta = new ObjectMetadata(); 
            meta.setContentLength(f.length()); 
            meta.setContentType(type);
            meta.setCacheControl("no-cache");
            meta.setContentEncoding("utf-8"); 
            ossClient.putObject(bucketName, fileName,input,meta); 
            url = ossUrl+"/"+fileName+"||01";
            resultMap.put("error", 0);
			resultMap.put("url", url);
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("error", 1);
			resultMap.put("message", "文件上传发生异常");
		} finally {  
            ossClient.shutdown();  
        } 
        return resultMap;  
    } 
}
